package com.xk857.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xk857.entities.SysRole;
import com.xk857.system.mapper.SysRoleMapper;
import com.xk857.system.req.SysRoleREQ;
import com.xk857.system.service.ISysRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xk857.util.base.Result;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 角色信息表 服务实现类
 *
 * @author CV大魔王
 * @since 2021-02-25
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {

    @Override
    public IPage<SysRole> queryPage(SysRoleREQ req) {
        QueryWrapper<SysRole> wrapper = new QueryWrapper<>();
        // 条件查询
        if (StringUtils.isNotEmpty(req.getName())) {
            wrapper.like("name", req.getName());
        }
        wrapper.orderByAsc("update_date");
        return baseMapper.selectPage(req.getPage(), wrapper);
    }


    @CachePut(value = "role_id_find_menu", key = "#id")
    @Override
    public List<String> findMenuIdsById(String id) {
        return baseMapper.findMenuIdsById(id);
    }


    @Override
    public Result saveRoleMenu(String roleId, List<String> menuIds) {
        // 1. 先删除角色菜单关系表数据
        baseMapper.deleteRoleMenuByRoleId(roleId);
        // 2. 再保存新的角色菜单关系表数据
        if (CollectionUtils.isNotEmpty(menuIds)) {
            baseMapper.saveRoleMenu(roleId, menuIds);
        }
        return Result.ok();
    }

    @CacheEvict(value = "role_id_find_menu", allEntries = true)
    @Override
    public Result deleteById(String id) {
        // 1. 通过角色 id 删除角色信息表数据
        baseMapper.deleteById(id);
        // 2. 通过角色 id 删除角色菜单关系表数据
        baseMapper.deleteRoleMenuByRoleId(id);
        return Result.ok();
    }
}
